package com.lx.bbs.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lx.bbs.entity.Result;
import com.lx.bbs.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if (session.getAttribute("myinfo") == null) {
            if (request.getHeader("Accept").startsWith("application/json")) {
                Result result = new Result(0, "未登录", null);
                String json = new ObjectMapper().writeValueAsString(result);
                response.getWriter().append(json);
            }else{
                // request.getRequestURL() 获取资源地址,  request.getQueryString() 获取后面的参数
                session.setAttribute("RequestURL", request.getRequestURL() + "?" + request.getQueryString());

                String contextPath = request.getServletContext().getContextPath();
                // 打开页面时提示用户必须先登录
                response.sendRedirect(contextPath + "/login.html?cause=1");
            }
            return false;
        }

        if (request.getServletPath().startsWith("/back")) {
            User myinfo = (User) session.getAttribute("myinfo");
            if (!"admin".equals(myinfo.getRole())) {
                if (request.getHeader("Accept").startsWith("application/json")) {
                    Result result = new Result(0, "权限不足", null);
                    String json = new ObjectMapper().writeValueAsString(result);
                    response.getWriter().append(json);
                }else{
                    session.setAttribute("RequestURL", request.getRequestURL()+ "?" + request.getQueryString());
                    String contextPath = request.getServletContext().getContextPath();
                    // TODO 打开页面时提示用户必须先登录
                    response.sendRedirect(contextPath + "/login.html?cause=2");
                }
                return false;
            }
        }
        return true;
    }
}
